package com.zh.mall.config;

import com.zh.mall.dto.AdminUserDetails;
import com.zh.mall.mbg.model.UmsAdmin;
import com.zh.mall.mbg.model.UmsPermission;
import com.zh.mall.service.UmsAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.List;

/**
 * mall-security模块相关配置
 * 自定义配置，用于配置如何获取用户信息及动态权限
 * @author ZhengHao
 * Created At 2022/7/19.
 **/
@Configuration
public class MallSecurityConfig {
    @Autowired
    private UmsAdminService umsAdminService;
    @Bean
    public UserDetailsService userDetailsService(){
        // 获取登录用户信息
        return username -> {
            UmsAdmin admin = umsAdminService.getAdminByUsername(username);
            if (admin != null){
                List<UmsPermission> permissionList = umsAdminService.getPermissionList(admin.getId());
                return new AdminUserDetails(admin,permissionList);
            }
            throw new UsernameNotFoundException("用户名或者密码错误");
        };
    }
}